package wildcard.servlet;

import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;

import wildcard.database.DBAccess;

public class TableRecordExecuteServlet extends HttpServlet {

	protected void doPost(javax.servlet.http.HttpServletRequest req,
			javax.servlet.http.HttpServletResponse resp)
			throws javax.servlet.ServletException, java.io.IOException {

		// 実行結果
		ArrayList<ArrayList<String>> resultSelect; // 更新後の出力レコード
		int countInsert = 0;
		String errorString = "";

		// SQL用パラメータ
		ArrayList<String> selectParameters = new ArrayList<String>();
		ArrayList<String> insertParameters = new ArrayList<String>();

		// HTTPの設定
		req.setCharacterEncoding("UTF-8");
		HttpSession session = req.getSession();

		// ユーザIDの取得
		LoginBean loginBean = (LoginBean) session.getAttribute("AndroidUser");
		String dbId = "AN";
		String dbPassword = "wildcard";

		try {
			String tableId = req.getParameter("tableid");
			String inputCustomers = req.getParameter("customers" + tableId);
			String currentCustomers = req.getParameter("currentCustomers"
					+ tableId);

			System.out.println(this.getClass() + " id " + tableId);
			System.out.println(this.getClass() + " input " + inputCustomers);
			System.out.println(this.getClass() + " current " + currentCustomers);

			insertParameters.clear();

			// 入力の判定 同じ値は受け付けない
			if (currentCustomers.equals(inputCustomers)) {
				RequestDispatcher dispatcher;
				dispatcher = req.getRequestDispatcher("android_main.jsp");
				dispatcher.forward(req, resp);
			}

			insertParameters.add(tableId);
			insertParameters.add(inputCustomers);

			// SQL文を取得するためにデータベースにアクセスする
			String sqlId = req.getParameter("sql");
			selectParameters = new ArrayList<String>();
			selectParameters.add(sqlId);
			resultSelect = DBAccess.executeSelect(dbId, dbPassword,
					DBAccess.SQL_SELECT_COMMAND, selectParameters);

			// アクセスした結果を格納する
			String sql = resultSelect.get(1).get(0);

			// 追加処理
			DBAccess.executeUpdate(dbId, dbPassword, sql, insertParameters);

		} catch (NullPointerException nullpo) {
			System.out.println("ｶﾞｯ");
			nullpo.printStackTrace();
		}

		// 元の画面へ遷移
		RequestDispatcher dispatcher;
		dispatcher = req.getRequestDispatcher("android_main.jsp");
		dispatcher.forward(req, resp);
	};

}
